package com.zut.Interceptor;


import com.alibaba.fastjson.JSONObject;
import com.zut.pojo.Result;
import com.zut.util.JwtUtils;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@CrossOrigin
public class LoginCheckInterceptor implements HandlerInterceptor {
    //controller方法之前运行
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        //1、获取请求参数
        String url = req.getRequestURI().toString();
        if (url.contains("login")||url.contains("register")||url.contains("adminLogin")||url.contains("telTest")){//登陆请求，放行
            return true;
        }
        if(HttpMethod.OPTIONS.toString().equals(req.getMethod())){
            System.out.println("OPTIONS请求，放行");
            return true;
        }
        //获取请求头的token,前端vue会给每一个请求都添加一个请求头
        String jwt = req.getHeader("Authorization");
        if (!StringUtils.hasLength(jwt)){//token为空
            Result error = Result.error("NOT_LOGIN");
            //手动转换为JSON数据
            String notLogin = JSONObject.toJSONString(error);

//            System.out.println(notLogin);
            resp.getWriter().write(notLogin);
            return false;
        }
        //如果有token,如果解析失败，返回错误结果（未登录）
        try{
            // 解析token
            JwtUtils.parseJWT(jwt);
        }catch (Exception e){
            e.printStackTrace();
            //解析失败
            Result error = Result.error("NOT_LOGIN");
            //手动转换为JSON数据
            String notLogin = JSONObject.toJSONString(error);
//            System.out.println(notLogin);
            resp.getWriter().write(notLogin);
            return false;
        }
        //6、放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
